#include "StdAfx.h"
#include <cutt/ChannelLoader.h>
#include <json/JsonParser.hpp>
#include <cutt/Http.h>
#include <cutt/Log.h>
using namespace json;
using namespace cutt;

ChannelLoader::ChannelLoader(void)
{
}

ChannelLoader::~ChannelLoader(void)
{
}

ChannelPage * ChannelLoader::LoadChannels(){
	//CMzString str(128);
	//wchar_t *buf = L"Channel%d";	


	//page.ChannelCount = CHANNEL_PAGE_SIZE;
	//return &page;

	//Http& session = global.httpSession;
	Http session;
	TCHAR url[512];
	//wsprintf(url,L"rest/%s?uid=%s&ua=%s&client=%s",
	//	global.apiChannels,
	//	global.deviceSN.C_Str(),
	//	global.apiHttpUA,
	//	global.apiHttpClient);
	LPTSTR  response;
	DWORD status(0);
	TCHAR * cookie(NULL);
	if(!session.DoGet(url,&response,&status,cookie)){
		LOG_ERROR("%d",session.GetError());
	}
	JsonParser parser;	
	JObject* jRoot = (JObject*)parser.parse(response);	
	JArray* jChannels = (JArray*)(*jRoot)[L"channels"];
	//ChannelPage& channelPage = *g_channelPool.getNextPage();
	ChannelPage channelPage;
	int index = -1;
	for(int i = 0;i < CHANNEL_PAGE_SIZE;++ i){		
		if(i >= jChannels->size()){
			break;;
		}
		JObject* jChannel = (JObject*)((*jChannels)[i]);
		Channel& channel = channelPage[index];
		channel.ChannelID = (jChannel->get<String>(L"id")).c_str();
		channel.Name = (jChannel->get<String>(L"name")).c_str();
	}
	
	//for(int i = 0;i < CHANNEL_PAGE_SIZE;++i){
	//	wsprintf(str.C_Str(), buf, i);
	//	Channel & channel = page[i];
	//	channel.ChannelID = str;
	//	channel.CreateTime = L"2008/8/8 20:08";
	//	channel.UpdateTime = L"2008/8/8 20:08";
	//	channel.Name = str;
	//}


	return &channelPage;
}

ChannelLoader g_channelLoader;